<template>
  <el-upload
    v-bind="$attrs"
    action="*"
    :accept="accept"
    :auto-upload="false"
    :show-file-list="false"
    :on-change="selectFileChange"
  >
    <slot :data="value">
      <div class="box">
        <div v-if="valueCopy" class="img">
          <img :src="valueCopy" class="avatar" />
          <i class="el-icon-close" @click.stop="deleteFn"></i>
          <slot name="picturePrefix" />
        </div>
        <i v-else class="el-icon-plus"></i>
      </div>
    </slot>
  </el-upload>
</template>

<script>
import { fileServerPath } from '@/config/app'
import { uploadFile } from '@/apiList/api_file'
import { local } from '@/utils/jcore/storage'
export default {
  name: 'UploadImage',
  props: {
    value: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: '.jpeg,.png,.jpg,.gif,.bmp'
    },
    // 自动补全
    completePath: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {}
  },
  computed: {
    valueCopy: {
      get() {
        return this.pathFormat(this.value)
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {},
  methods: {
    async selectFileChange(file) {
      const f = new FormData()
      f.append('file', file.raw)

      f.append('creator', local.get('authorityList').id)
      const res = await uploadFile(f)
      const fid = res.fileInfos[0].fid
      const filePath = this.pathFormat(fid)
      this.$emit('input', this.completePath ? filePath : fid)
      this.$emit('change', { fid, filePath, file })
    },
    deleteFn() {
      this.$confirm('确定删除吗?')
        .then(() => {
          this.valueCopy = ''
        })
        .catch(() => {})
    },
    pathFormat(val) {
      if (val && val.indexOf('?fid=') === -1 && val.indexOf('http') === -1) {
        return `${fileServerPath}/oss/downloadFile?fid=${val}`
      } else {
        return val
      }
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  border: 1px solid #c0ccda;
  .img {
    position: relative;
    .el-icon-close {
      position: absolute;
      top: -10px;
      right: -10px;
      width: 25px;
      height: 25px;
      text-align: center;
      line-height: 25px;
      color: red;
      border-radius: 50%;
      background-color: #f0f0ed;
      font-size: 20px;
    }
    img {
      width: 200px;
      max-height: 500px;
    }
  }
  .el-icon-plus {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 280px;
    font-size: 50px;
    color: #8c939d;
  }
}
</style>
